import axios from 'axios'
import config from '../configs/request'
import store from '../store'

// create an axios instance
const request = axios.create({
    baseURL: config.baseUrl,
    timeout: 20000 // request timeout
})

// request interceptor
request.interceptors.request.use(config => {
    const token = localStorage.getItem('token')

    if (token) {
        config.headers['Authorization'] = "Bearer " + token
    }

    if (config['label']) {
        store.commit('loading/setTrue', config['label'])
        if (config['show_loading']) {
            store.dispatch('message/showLoading', '').then(loading => {
                request[config['label']] = loading
            })
        }
    }

    config.withCredentials = true   // 跨域时发送带凭证的请求

    return config
}, error => {
    // Do something with request error
    console.log('http request error: ', error) // for debug
})

// response interceptor
request.interceptors.response.use(
    // response => response,
    response => {
        const res = response.data

        if (response.config?.label) {
            store.commit('loading/setFalse', response.config['label'])
            if (response.config?.show_loading) {
                request[response.config['label']].clear()
            }
        }

        if (res.code !== 0) {
            store.dispatch('message/showError', ('[' + res.code + ']' + res?.message)).then(r => {})
            return Promise.reject(res)
        } else {
            // return response.data
            if (res?.message) {
                store.dispatch('message/showSuccess', res?.message).then(r => {})
            }
            return Promise.resolve(response)
        }
    },
    (error) => {
        if (error?.response?.status == 412) {
            store.dispatch("user/toLogin").then(r => {})
            store.dispatch('message/showError', '您还没有登录~').then(r => {})
        } else {
            store.dispatch('message/showError', '网络异常').then(r => {})
        }
        return Promise.reject(error)
    })

export default request